package com.ruoyi.web.controller.app;


import cn.dev33.satoken.annotation.SaIgnore;
import com.ruoyi.app.domain.AppUser;
import com.ruoyi.app.domain.vo.AppUserVo;
import com.ruoyi.app.mapper.AppUserMapper;
import com.ruoyi.app.service.*;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BillType;
import com.ruoyi.common.enums.CoinType;
import com.ruoyi.common.enums.DetailEnums;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/advertising")
public class AppAdvertisingController extends BaseController {

    private final IAppUserService appUserService;
    private final IAppAssetService appAssetService;
    private final IAppDetailService appDetailService;
    private final IAppUserVipService appUserVipService;
    private final IAppPackageOrderService appPackageOrderService;
    private final AppUserMapper appUserMapper;


    @PostMapping("/sign2")
    @SaIgnore
    public R<?> sign2() {
        //查询所有用户
        List<AppUser> appUsers = appUserMapper.selectList();
        for (AppUser appUser : appUsers) {
            String key7 = "7dayContribution:" + appUser.getId();
            if (RedisUtils.hasKey(key7)){
                Object cacheObject = RedisUtils.getCacheObject(key7);
                if (cacheObject.toString().equals("7") || (int)cacheObject > 7){
                    if (appUser.getCode()!=null){
                        continue;
                    }
                    if (appUser.getParentId()==null){
                        continue;
                    }
                    appAssetService.subContribution(appUser.getParentId(), new BigDecimal(5));
                    appDetailService.insert(appUser.getParentId(), new BigDecimal(5), BigDecimal.ZERO,
                            BillType.TO.getCode(), CoinType.CONTRIBUTION.getCode(), DetailEnums.REGISTER_REWARD.getCode(),
                            "未实名扣除", null);
                }

            }
        }



        return R.ok();
    }

    /**
     * 签到
     *
     * @return
     */
    @PostMapping("/sign")
    public R<?> sign() {
        Long id = getUserId();
        AppUserVo myUserVo = appUserService.queryById(id);
        if (!StringUtils.equals(myUserVo.getStatus(), Constants.SUCCESS)) {
            return R.fail("账号已被冻结或注销，请联系客服或管理员！");
        }
        String endTime = appUserVipService.userVip(id);
        if (StringUtils.isBlank(endTime)) {
            return R.fail("开通VIP会员才可以免看广告");
        }
        String key = CacheConstants.ADVERTISING + id;
        Integer count = RedisUtils.getCacheObject(key);
        if (count == null) {
            count = 0;
        }
        if (count >= CacheConstants.TODAY_ADVERTISING_NUMBER) {
            return R.fail("今日已签到");
        }
        appPackageOrderService.dayDownOrder(id);
        count = CacheConstants.TODAY_ADVERTISING_NUMBER;
        RedisUtils.setCacheObject(key, count, Duration.ofSeconds(DateUtils.seconds()));
        BigDecimal integral = new BigDecimal(CacheConstants.REWARD_NUMBER).multiply(new BigDecimal(count));
//        appAssetService.addIntegral(id, integral);
//        appDetailService.insert(id, integral, BigDecimal.ZERO, BillType.IN.getCode(), CoinType.INTE.getCode(), DetailEnums.SEE_ADS.getCode(), DetailEnums.SEE_ADS.getInfo(), null);
       // appUserService.adRewards(id, integral);
        return R.ok("签到成功");
    }


    /**
     * 获取今日看广告数量
     *
     * @return
     */
    @GetMapping("/getNumber")
    public R<?> getNumber() {
        String key = CacheConstants.ADVERTISING + getUserId();
        Integer count = RedisUtils.getCacheObject(key);
        if (count == null) {
            count = 0;
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("number", count);
        map.put("maxNumber", CacheConstants.TODAY_ADVERTISING_NUMBER);
        return R.ok(map);
    }


    /**
     * 设置今日看广告次数
     *
     * @return
     */
    @PostMapping("/setNumber")
    public R<?> setNumber(
        @RequestParam(name = "number") Integer number,
        @RequestParam(name = "type", defaultValue = "1") String type
    ) {
        String typeKey;
        Integer maxNumber;
        Long id = getUserId();
        AppUserVo myUserVo = appUserService.queryById(id);
        if (!StringUtils.equals(myUserVo.getStatus(), Constants.SUCCESS)) {
            return R.fail("账号已被冻结或注销，请联系客服或管理员！");
        }
        if (StringUtils.equals(type, Constants.FAIL)) {
            typeKey = CacheConstants.ADVERTISING;
            maxNumber = CacheConstants.TODAY_ADVERTISING_NUMBER;
        } else {
            typeKey = CacheConstants.TASK_ADVERTISING;
            maxNumber = CacheConstants.TODAY_TASK_ADVERTISING_NUMBER;
        }
        String key = typeKey + id;
        Integer count = RedisUtils.getCacheObject(key);
        if (count == null) {
            count = 0;
        }
        if (count >= maxNumber) {
            return R.fail("今日广告已看完");
        }
        count = count + number;
        if (count >= maxNumber && StringUtils.equals(type, Constants.FAIL)) {
            appPackageOrderService.dayDownOrder(id);
        }
        String key7 = "7dayContribution:" + id;
        if (count==6){
            if (RedisUtils.hasKey(key7)){
                Object cacheObject = RedisUtils.getCacheObject(key7);
                cacheObject = (Integer) cacheObject + 1;
                RedisUtils.setCacheObject(key7, cacheObject);
                if (Integer.parseInt(cacheObject.toString()) >= 8){
                    RedisUtils.setCacheObject(key7, 1);
                }
                if (myUserVo.getCode()!=null){
                    if (cacheObject.toString().equals("7")){
                        appAssetService.addContribution(id, new BigDecimal(5));
                        appDetailService.insert(id, new BigDecimal(5), BigDecimal.ZERO,
                                BillType.IN.getCode(), CoinType.CONTRIBUTION.getCode(), DetailEnums.REGISTER_REWARD.getCode(),
                                "连续看广告奖励", null);
                        //给上级增加贡献值
                        if (myUserVo.getParentId()!=null){
                            appAssetService.addContribution(myUserVo.getParentId(), new BigDecimal(5));
                            appDetailService.insert(myUserVo.getParentId(), new BigDecimal(5), BigDecimal.ZERO,
                                    BillType.IN.getCode(), CoinType.CONTRIBUTION.getCode(), DetailEnums.REGISTER_REWARD.getCode(),
                                    "下级连续看广告奖励", null);
                        }
                    }
                }
            }else {
                RedisUtils.setCacheObject(key7, 1);
            }
        }
        RedisUtils.setCacheObject(key, count, Duration.ofSeconds(DateUtils.seconds()));
        BigDecimal integral = new BigDecimal(CacheConstants.REWARD_NUMBER);
        appAssetService.addIntegral(id, integral);
        appDetailService.insert(id, integral, BigDecimal.ZERO, BillType.IN.getCode(), CoinType.INTE.getCode(), DetailEnums.SEE_ADS.getCode(), DetailEnums.SEE_ADS.getInfo(), null);
        // appUserService.adRewards(id, integral);
        HashMap<String, Object> map = new HashMap<>();
        map.put("number", count);
        map.put("maxNumber", maxNumber);
        return R.ok(map);
    }


    /**
     * 爬塔签到
     *
     * @return
     */
    @PostMapping("/ptSign")
    public R<?> ptSign() {
        Long id = getUserId();
        AppUserVo myUserVo = appUserService.queryById(id);
        if (!StringUtils.equals(myUserVo.getStatus(), Constants.SUCCESS)) {
            return R.fail("账号已被冻结或注销，请联系客服或管理员！");
        }
        String endTime = appUserVipService.userVip(id);
        if (StringUtils.isBlank(endTime)) {
            return R.fail("开通VIP会员才可以免看广告");
        }
        String key = CacheConstants.TASK_ADVERTISING + id;
        Integer count = RedisUtils.getCacheObject(key);
        if (count == null) {
            count = 0;
        }
        Integer max = CacheConstants.TODAY_TASK_ADVERTISING_NUMBER;
        if (count >= max) {
            return R.fail("今日已签到");
        }
        count = max;
        RedisUtils.setCacheObject(key, count, Duration.ofSeconds(DateUtils.seconds()));
        BigDecimal integral = new BigDecimal(CacheConstants.REWARD_NUMBER).multiply(new BigDecimal(count));
        appAssetService.addIntegral(id, integral);
        appDetailService.insert(id, integral, BigDecimal.ZERO, BillType.IN.getCode(), CoinType.INTE.getCode(), DetailEnums.SEE_ADS.getCode(), DetailEnums.SEE_ADS.getInfo(), null);
        appUserService.adRewards(id, integral);
        return R.ok("签到成功");
    }


    /**
     * 获取爬塔今日看广告数量
     *
     * @return
     */
    @GetMapping("/getPtNumber")
    public R<?> getPtNumber() {
        String key = CacheConstants.TASK_ADVERTISING + getUserId();
        Integer count = RedisUtils.getCacheObject(key);
        if (count == null) {
            count = 0;
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("number", count);
        map.put("maxNumber", CacheConstants.TODAY_TASK_ADVERTISING_NUMBER);
        return R.ok(map);
    }
}
